package cn.lger.icollege.service;

import cn.lger.icollege.dao.AttendanceMessageDao;
import cn.lger.icollege.dao.ClassRoomDao;
import cn.lger.icollege.dao.TeacherDao;
import cn.lger.icollege.entity.AttendanceMessage;
import cn.lger.icollege.entity.Classroom;
import cn.lger.icollege.entity.Teacher;
import cn.lger.icollege.util.SecurityResourceUtil;
import org.springframework.data.domain.Sort;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * Code that Changed the World
 * Pro said
 * Created by Pro on 2018-04-23.
 */
@Service
public class TeacherService {
    @Resource
    private AttendanceMessageDao attendanceMessageDao;

    @Resource
    private TeacherDao teacherDao;

    @Resource
    private ClassRoomDao classRoomDao;

    @Resource
    private PasswordEncoder encoder;

    public List<AttendanceMessage> findAllByToTeacher(String username) {
        return attendanceMessageDao.findAllByToTeacher(username, Sort.by(Sort.Direction.ASC, "hasRead"));
    }

    @Transactional
    public AttendanceMessage readMessage(String id, String username) {
        Optional<AttendanceMessage> optional = attendanceMessageDao.findById(id);
        if (optional.isPresent()){
            AttendanceMessage message = optional.get();
            if (!message.getToTeacher().equals(username))
                throw new RuntimeException("你是一个假老师");
            message.setHasRead(true);
            Teacher teacher = message.getAttendance().getTeacher();
            if (teacher.getNews() - 1 >= 0)
                teacher.setNews(teacher.getNews() - 1);
            return attendanceMessageDao.save(message);
        }
        return null;
    }

    @Transactional
    public Teacher editTeacher(Teacher teacher){
        Teacher teacherdb=teacherDao.findById(SecurityResourceUtil.getUserDetailsUsername()).get();
        teacherdb.setName(teacher.getName());
        teacherdb.setAddress(teacher.getAddress());
        teacherdb.setPhone(teacher.getPhone());
        if(teacher.getPassword()!=null&&!"".equals(teacher.getPassword())){
            teacherdb.setPassword(encoder.encode(teacher.getPassword()));
        }
        return  teacherDao.save(teacherdb);
    }

    public Teacher findTeacherByUsername(String username){
        Optional<Teacher> optional = teacherDao.findById(username);
        return optional.orElse(null);
    }

    @Transactional
    public Teacher updateTeacher(Teacher teacher) {
        Optional<Teacher> teacherOptional = teacherDao.findById(teacher.getUsername());
        if (teacherOptional.isPresent()){
            Teacher temp = teacherOptional.get();
            if (teacher.getIconPath() != null && !"icon/common.jpg".equals(teacher.getIconPath())){
                temp.setIconPath(teacher.getIconPath());
            }
            if (teacher.getPassword() != null && !"".equals(teacher.getPassword().trim()))
                temp.setPassword(encoder.encode(teacher.getPassword()));
            temp.setPhone(teacher.getPhone() == null? temp.getPhone() : teacher.getPhone());
            temp.setAddress(teacher.getAddress() == null? temp.getAddress() : teacher.getAddress());
            return teacherDao.save(temp);
        }
        return null;
    }

    @Transactional
    public Teacher saveTeacher(Teacher teacher) {
        teacher.setPassword(encoder.encode(teacher.getPassword()));
        return teacherDao.save(teacher);
    }

    @Transactional
    public void deleteTeacher(String username) {
        teacherDao.deleteById(username);
    }

    public List<Teacher> findAll() {
        return teacherDao.findAll();
    }

    @Transactional
    public List<Classroom> updateTeacherClassrooms(String username, Long[] classIds) {

        Optional<Teacher> optional = teacherDao.findById(username);
        if (optional.isPresent()){
            Teacher teacher = optional.get();
            List<Classroom> classroomList = classRoomDao.findByTeachersIs(teacher);
            for (Classroom classroom : classroomList){
                classroom.getTeachers().remove(teacher);
            }
            classRoomDao.saveAll(classroomList);
            if (classIds != null) {
                classroomList = classRoomDao.findAllById(Arrays.asList(classIds));
                for (Classroom classroom : classroomList) {
                    classroom.getTeachers().add(teacher);
                }
                classRoomDao.saveAll(classroomList);
                return classroomList;
            }
            return new ArrayList<>();
        }
        throw new RuntimeException("教师不存在");
    }
}
